import java.util.HashMap;
import java.util.Map;

public class Leet42 {
	public static void main(String[] args) {
		System.out.println(trap(new int[]{}));
	}
	
	static public int trap(int[] height) {
		if(height.length==0)
			return 0;
		int num = 0;
		int[] L = new int[height.length],R = new int[height.length];
		L[0] = height[0];
		for(int i = 1;i<height.length;i++) {
			L[i] = Math.max(height[i],L[i-1]);
		}
		R[height.length-1] = height[height.length-1];
		for(int i = height.length-2;i>0;i--) {
			R[i] = Math.max(height[i],R[i+1]);
		}
		for(int i = 1;i<height.length-1;i++)
				num+=Math.min(L[i], R[i])>height[i]?Math.min(L[i], R[i])-height[i]:0;
		return num;
    }
}
